package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.user.request.UserActivityQueryRequest;
import com.blog.cmrpersonalblog.dto.user.response.AdminUserProfileResponse;
import com.blog.cmrpersonalblog.service.UserActivityService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户活动记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/user-activity")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserActivityController {

   @Resource
    private UserActivityService userActivityService;

    /**
     * 分页查询用户活动记录
     */
    @GetMapping("/list")
    @SaCheckRole("admin")
    public Result<IPage<AdminUserProfileResponse.ActivityRecord>> getActivityList(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) List<String> activityTypes,
            @RequestParam(required = false) String typeGroup,
            @RequestParam(required = false) String result,
            @RequestParam(required = false) String ipAddress,
            @RequestParam(required = false) String timeRange,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String targetType,
            @RequestParam(required = false) Long targetId,
            @RequestParam(defaultValue = "false") Boolean importantOnly,
            @RequestParam(defaultValue = "create_time") String orderBy,
            @RequestParam(defaultValue = "desc") String orderDirection,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        try {
            UserActivityQueryRequest query = new UserActivityQueryRequest();
            query.setUserId(userId);
            query.setActivityTypes(activityTypes);
            query.setTypeGroup(typeGroup);
            query.setResult(result);
            query.setIpAddress(ipAddress);
            query.setKeyword(keyword);
            query.setTargetType(targetType);
            query.setTargetId(targetId);
            query.setImportantOnly(importantOnly);
            query.setOrderBy(orderBy);
            query.setOrderDirection(orderDirection);
            query.setPage(page);
            query.setSize(size);
            
            // 设置时间范围
            if (timeRange != null && !timeRange.isEmpty()) {
                query.setTimeRange(timeRange);
            }
            
            IPage<AdminUserProfileResponse.ActivityRecord> activities = 
                userActivityService.getActivityPage(query);
            
            return Result.success(activities);
        } catch (Exception e) {
            log.error("查询用户活动记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户最近活动记录
     */
    @GetMapping("/recent/{userId}")
    @SaCheckRole("admin")
    public Result<List<AdminUserProfileResponse.ActivityRecord>> getRecentActivities(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<AdminUserProfileResponse.ActivityRecord> activities = 
                userActivityService.getRecentActivities(userId, limit);
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取用户最近活动记录失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取活动统计信息
     */
    @GetMapping("/statistics")
    @SaCheckRole("admin")
    public Result<Map<String, Object>> getActivityStatistics(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "30") Integer days) {
        try {
            Map<String, Object> statistics = userActivityService.getActivityStatistics(userId, days);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取活动统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 清理过期活动记录
     */
    @PostMapping("/clean-expired")
    @SaCheckRole("admin")
    public Result<String> cleanExpiredActivities() {
        try {
            Integer cleanedCount = userActivityService.cleanExpiredActivities();
            return Result.success(String.format("成功清理%d条过期活动记录", cleanedCount));
        } catch (Exception e) {
            log.error("清理过期活动记录失败", e);
            return Result.error("清理失败：" + e.getMessage());
        }
    }

    /**
     * 获取活动类型分组信息
     */
    @GetMapping("/type-groups")
    @SaCheckRole("admin")
    public Result<Map<String, Object>> getActivityTypeGroups() {
        try {
            Map<String, Object> typeGroups = Map.of(
                "AUTH", Map.of("name", "认证相关", "types", List.of("LOGIN", "LOGOUT", "LOGIN_FAILED", "PASSWORD_CHANGED")),
                "MANAGEMENT", Map.of("name", "管理操作", "types", List.of("USER_CREATED", "USER_UPDATED", "USER_DELETED", 
                    "USER_STATUS_CHANGED", "USER_ROLE_ASSIGNED", "USER_ROLE_REMOVED", "ROLE_CREATED", "ROLE_UPDATED", 
                    "ROLE_DELETED", "PERMISSION_ASSIGNED", "PERMISSION_REMOVED")),
                "CONTENT", Map.of("name", "内容管理", "types", List.of("ARTICLE_PUBLISHED", "ARTICLE_UPDATED", 
                    "ARTICLE_DELETED", "ARTICLE_STATUS_CHANGED")),
                "SOCIAL", Map.of("name", "社交互动", "types", List.of("USER_FOLLOWED", "USER_UNFOLLOWED", 
                    "ARTICLE_LIKED", "ARTICLE_COLLECTED", "COMMENT_POSTED")),
                "SYSTEM", Map.of("name", "系统管理", "types", List.of("SYSTEM_CONFIG_CHANGED", "DATA_EXPORT", 
                    "DATA_IMPORT", "SECURITY_VIOLATION", "FILE_UPLOADED", "FILE_DELETED")),
                "IMPORTANT", Map.of("name", "重要操作", "description", "只显示重要的操作记录")
            );
            
            return Result.success(typeGroups);
        } catch (Exception e) {
            log.error("获取活动类型分组信息失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取时间范围选项
     */
    @GetMapping("/time-ranges")
    @SaCheckRole("admin")
    public Result<Map<String, String>> getTimeRanges() {
        try {
            Map<String, String> timeRanges = Map.of(
                "TODAY", "今天",
                "YESTERDAY", "昨天", 
                "LAST_7_DAYS", "最近7天",
                "LAST_30_DAYS", "最近30天",
                "LAST_90_DAYS", "最近90天"
            );
            
            return Result.success(timeRanges);
        } catch (Exception e) {
            log.error("获取时间范围选项失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
}
